#/usr/bin/python
# coding: utf8

import time
from  PAM30 import PAM30
import sys
import win32api
import win32con
import win32gui

reload(sys)
sys.setdefaultencoding("utf-8")


def jumpIEtab():
    '''
    跳转ctl+Tab,ie8的跳到下一个窗口的快捷键
    '''
    win32api.keybd_event(17, 0, 0, 0)#ctrl
    win32api.keybd_event(9, 0, 0, 0)#tab
    win32api.keybd_event(9, 0, win32con.KEYEVENTF_KEYUP, 0)
    win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)


def setRegValue(keystr, vname, value):
    '''
    设置某个注册表项的值，不存在则先添加项再设置值
    '''
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keystr, 0, win32con.KEY_ALL_ACCESS)
    try:
        kv = win32api.RegQueryValueEx(key, vname)
        if(kv):
            return True
    except:
        win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
        win32api.RegCloseKey(key)
        return True


def ordd(str):
    '''
    解决键盘码不对应问题,不知道别的电脑有没有这个问题
    '''
    t = ord(str)
    #65到90是A到Z
    if(t>90):
        return t-32
    else:
        return t


def typeme(passw):
    '''
    模拟人工输入,自动输入参数字符串到焦点窗口
    '''
    psht = len(passw)
    for j in range(psht):
        win32api.keybd_event(ordd(passw[j]), 0, 0, 0)
        time.sleep(0.5)
        win32api.keybd_event(ordd(passw[j]), 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(0.5)


def lgTaobao(username, userpass):
    '''
    使用指定用户名密码（在IE）登录淘宝
    '''
    #lgurl = 'https://login.taobao.com/member/login.jhtml?spm=2013.1.0.2'
    lgurl = 'https://login.taobao.com/member/login.jhtml?redirectURL=http%3A%2F%2Fi.taobao.com%2Fmy_taobao.htm%3Fspm%3D1.1000386.0.10'
    ie.navigate(lgurl)
    ie.setTextBox('TPL_username', username.decode('utf-8'))
    ie.setCheckBox('J_SafeLoginCheck', 0)
    bt = ie.findElement('button', 'id', 'J_SubmitStatic')
    #ie.clickButton('J_SubmitStatic')
    ie.clickElement(bt)
    ie.setTextBox('TPL_password', userpass)
    typeme(userpass)
    time.sleep(0.5)
    bt = ie.findElement('button', 'id', 'J_SubmitStatic')
    ie.clickElement(bt)
    if(ie.findText(username)):
        return True
    else:
        return False


def exitTaobao(username):
    '''
    退出当前登录状态（使用给定帐号退出）
    '''
    isLogin = ie.findText(username)
    if(isLogin):
        #ie.clickLink('退出')
        ie.clickHiddenLink('J_Logout')
        isLogout = not(ie.findText(username))
        if(isLogout):
            return True
        else:
            return False
    else:
        win32gui.MessageBox(0, '未登录！'.decode('utf-8'), 'Notice!', 0)


def clickColor():
    '''
    点击商品的颜色等选项，参数为选项文字
    最多三个选项
    '''
    c1 = ie.findElement('span', 'innerText', s1)
    f = ie.clickElement(c1)
    print f


def addItem2cart():
    '''
    拍下某个宝贝，加入购物车
    '''
    isAddok = ie.clickLink('加入购物车')
    if(isAddok):
        time.sleep(1)
        ie.clickLink('<span>关闭</span>')
        return True
    else:
        win32gui.MessageBox(0, '设置数量失败！'.decode('utf-8'), 'Notice!', 0)


def payCart():
    '''
    支付购物车的订单,默认是在登录状态下
    '''
    isClickcart = ie.clickLink('mc-menu-hd')
    if(isClickcart):
        btn = ie.findElement('button', 'id', 'J_Go')#购物车结算
        if(ie.clickElement(btn)):
            time.sleep(0.5)
            btnf = ie.findElement('button', 'id', 'J_Go')#购物车提交订单
            if(ie.clickElement(btnf)):
                time.sleep(1)#进入支付页面
    else:
        win32gui.MessageBox(0, '进入购物车失败！'.decode('utf-8'), 'Notice!', 0)


def setCount(count):
    '''
    设置商品页面的购买数量
    '''
    isSetok = ie.setTextBox('J_IptAmount', count)
    if(isSetok):
            return True
    else:
        win32gui.MessageBox(0, '设置数量失败！'.decode('utf-8'), 'Notice!', 0)


def searchWd(sword, itemid, itemname):
    '''
    根据提供的关键词进行搜索，遍历1-10页寻找商品id
    找到后点击商品页面，切换界面到新IE窗口
    '''
    ie.navigate('http://www.taobao.com')
    ie.setTextBox('q', sword)
    ie.submitForm('search')
    #ie.clickButton('搜索')
    time.sleep(2)
    isFindItem = ie.findText(itemid)
    if(isFindItem):
        #找到淘宝id，然后点击商品链接
        #print ("find "+taoid.encode('gbk'))
        pdt = ie.findElement('a', 'title', itemname)
        #IE8要设置总是允许来自s.taobao.com的弹出窗口
        ie.clickElement(pdt)
        time.sleep(2)

        consis = str(pdt).find('tmall')
        if(consis == -1):
            ie.changeWindow(itemname+'-淘宝网')
        else:
            ie.changeWindow(itemname+'-tmall.com天猫')
        #跳转ctl+Tab,ie8的跳到下一个窗口的快捷键
        jumpIEtab()
        return True
    else:
        win32gui.MessageBox(0, '商品未找到！'.decode('utf-8'), 'Notice!', 0)
        return False


#允许淘宝的弹出窗口
keystr = 'SOFTWARE\\Microsoft\\Internet Explorer\\New Windows\\Allow'
setRegValue(keystr, 's.taobao.com', '0')


ie= PAM30.PAMIE()
sword = u'时尚简约双人电脑桌书架组合 家用台式书桌书柜书橱办公桌'
taoid = '蓝月亮家具公司'
itemid = '15171926168'
itemname = '时尚简约双人电脑桌书架组合 家用台式书桌书柜书橱办公桌'
#http://item.taobao.com/item.htm?id=15171926168
s1 = '白色1.6米'
searchWd(sword, itemid, itemname)
win32api.Beep(300, 200)
